import React, { useEffect, useRef, useState } from 'react';
import {
  Form,
  Input,
  Modal,
  Select,
  DatePicker,
  Row,
  Col,
  message,
} from 'antd';
import {
  adminCompanyType,
  adminPriceType,
  orderStateEnumType,
} from '@/utils/constant';
import { useRequest, useUpdateEffect } from '@umijs/hooks';
import {
  apiCustomerGetList,
  apiOrderGetList,
  apiProductGetList,
  apiProductLineGetList,
  apiPurchaseGetList,
} from '@/services/otherServices';
import moment from 'moment';
import { uniqBy } from '@/utils/utils';

const FormItem = Form.Item;
const Detail = (props: any) => {
  const {
    visible,
    onCancel,
    onOk,
    getForm,
    loading,
    afterClose,
    editId,
  } = props;
  const [form] = Form.useForm();
  const [customerValue, setCustomerValue] = useState('');
  const [customerData, setCustomerData] = useState([]);

  const [orderSearchValue, setOrderSearchValue] = useState('');
  const [orderData, setOrderData] = useState([]);

  const [oderDisabled, setOderDisabled] = useState(false);

  const [lineData, setLineData] = useState([]);
  const [lineValue, setLineValue] = useState('');

  const [data, setData] = useState([]);
  const [searchValue, setSearchValue] = useState('');

  const [productName, setProductName] = useState('');
  const [color, setColor] = useState('');
  const [attribute, setAttribute] = useState('');
  const [grade, setGrade] = useState('');

  const [colorData, setColorData]: any = useState([]);
  const [colorSearchValue, setColorSearchValue] = useState('');

  const [attributeData, setAttributeData]: any = useState([]);
  const [attributeSearchValue, setAttributeSearchValue] = useState('');

  const [gradeData, setGradeData]: any = useState([]);
  const [gradeSearchValue, setGradeSearchValue] = useState('');

  const [disabled, setDisabled] = useState(true);

  const { loading: colorLoading, run: runColor } = useRequest(
    apiProductGetList,
    {
      manual: true,
      throttleInterval: 500,
      onSuccess: (res, params) => {
        const newArr = uniqBy(res.data, 'color');
        setColorData(newArr);
      },
    },
  );

  useUpdateEffect(() => {
    runColor({
      color: colorSearchValue,
      productName: productName,
      pageNo: 1,
      pageSize: 100,
    });
  }, [colorSearchValue]);

  const { loading: gradeLoading, run: runGrade } = useRequest(
    apiProductGetList,
    {
      manual: true,
      throttleInterval: 500,
      onSuccess: (res, params) => {
        const newArr = uniqBy(res.data, 'grade');
        setGradeData(newArr);
      },
    },
  );

  useUpdateEffect(() => {
    runGrade({
      color: color,
      productName: productName,
      grade: gradeSearchValue,
      pageNo: 1,
      pageSize: 100,
    });
  }, [gradeSearchValue]);

  const { loading: attributeLoading, run: runAttribute } = useRequest(
    apiProductGetList,
    {
      manual: true,
      throttleInterval: 500,
      onSuccess: (res, params) => {
        res.data.forEach((n: any) => {
          if (n.attribute === '') {
            n.attribute = ' ';
          }
        });
        setAttributeData(res.data);
      },
    },
  );

  useUpdateEffect(() => {
    runAttribute({
      color: color,
      productName: productName,
      attribute: attributeSearchValue,
      grade: grade,
      pageNo: 1,
      pageSize: 100,
    });
  }, [attributeSearchValue]);

  const { loading: getProductName, run } = useRequest(apiProductGetList, {
    manual: true,
    throttleInterval: 500,
    onSuccess: (res, params: any) => {
      let result: any = undefined;
      res.data.forEach((n: any) => {
        if (n.attribute === null) {
          n.attribute = '';
        }
        if (
          n.attribute === params[0].attribute &&
          n.productName === params[0].productName &&
          n.color === params[0].color &&
          n.grade === params[0].grade
        ) {
          result = n;
        }
      });
      if (result) {
        setDisabled(false);
        form.setFieldsValue({
          productId: result.id,
          unit: result.unit,
        });
      }
    },
  });

  const { loading: lineDataLoading, run: getLineData } = useRequest(
    apiProductLineGetList,
    {
      manual: true,
      throttleInterval: 500,
      onSuccess: (res, params) => {
        setLineData(res.data);
      },
    },
  );

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 4 },
      md: { span: 4 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 18 },
      md: { span: 18 },
    },
  };

  const { loading: customerLoading, run: getCustomerList } = useRequest(
    apiCustomerGetList,
    {
      manual: true,
      throttleInterval: 500,
      onSuccess: (res, params) => {
        setCustomerData(res.data);
      },
    },
  );

  const { loading: getOrderListLoading, run: runOrderList } = useRequest(
    apiOrderGetList,
    {
      manual: true,
      throttleInterval: 500,
      onSuccess: (res, params) => {
        setOrderData(res.data);
      },
    },
  );

  useUpdateEffect(() => {
    getCustomerList({
      customerCompany: customerValue,
      pageNo: 1,
      pageSize: 10,
    });
  }, [customerValue]);

  useUpdateEffect(() => {
    runOrderList({
      orderNo: orderSearchValue,
      pageNo: 1,
      pageSize: 10,
    });
  }, [orderSearchValue]);

  useUpdateEffect(() => {
    getLineData({
      productLine: lineValue,
      pageNo: 1,
      pageSize: 10,
    });
  }, [lineValue]);

  useEffect(() => {
    getForm(form);
    getLineData({
      pageNo: 1,
      pageSize: 10,
    });
    runOrderList({
      pageNo: 1,
      pageSize: 10,
    });
    getCustomerList({
      pageNo: 1,
      pageSize: 10,
    });
  }, []);

  useUpdateEffect(() => {
    if (visible === true) {
      runOrderList({
        pageNo: 1,
        pageSize: 10,
      });
    }
  }, [visible]);

  useUpdateEffect(() => {
    if (visible === true && editId !== undefined) {
      if (form.getFieldValue('productId') !== undefined) {
        setDisabled(false);
      }
      if (form.getFieldValue('color') !== undefined) {
        runColor({
          productName: form.getFieldValue('productName'),
          pageNo: 1,
          pageSize: 200,
        });
      }
      if (form.getFieldValue('grade') !== undefined) {
        runGrade({
          productName: form.getFieldValue('productName'),
          color: form.getFieldValue('color'),
          pageNo: 1,
          pageSize: 200,
        });
        runAttribute({
          productName: form.getFieldValue('productName'),
          color: form.getFieldValue('color'),
          grade: form.getFieldValue('grade'),
          pageNo: 1,
          pageSize: 200,
        });
      }
      if (
        form.getFieldValue('attribute') !== undefined &&
        form.getFieldValue('attribute') === ''
      ) {
        form.setFieldsValue({
          attribute: ' ',
        });
      }
    }
  }, [visible, editId]);

  const onValuesChange = (changedValues: any, allValues: any) => {
    if (changedValues.productName) {
      setProductName(changedValues.productName);
      runColor({
        productName: changedValues.productName,
        pageNo: 1,
        pageSize: 200,
      });
      form.setFieldsValue({
        color: undefined,
        grade: undefined,
        attribute: undefined,
        unit: undefined,
      });
      setGradeData([]);
      setAttributeData([]);
    }

    if (changedValues.color) {
      setColor(changedValues.color);
      runGrade({
        productName: allValues.productName,
        color: changedValues.color,
        pageNo: 1,
        pageSize: 200,
      });
      form.setFieldsValue({
        grade: undefined,
        attribute: undefined,
        unit: undefined,
      });
      setAttributeData([]);
    }

    if (changedValues.grade) {
      setGrade(changedValues.grade);
      runAttribute({
        productName: allValues.productName,
        color: allValues.color,
        grade: changedValues.grade,
        pageNo: 1,
        pageSize: 200,
      });
      form.setFieldsValue({
        unit: undefined,
        attribute: undefined,
      });
    }
    if (changedValues.attribute === null || changedValues.attribute === '') {
      form.setFieldsValue({
        attribute: ' ',
      });
      run({
        productName: allValues.productName,
        color: allValues.color,
        grade: allValues.grade,
        attribute: ' ',
        pageNo: 1,
        pageSize: 100,
      });
    } else if (changedValues.attribute) {
      run({
        productName: allValues.productName,
        color: allValues.color,
        grade: allValues.grade,
        attribute: changedValues.attribute,
        pageNo: 1,
        pageSize: 100,
      });
    }

    if (changedValues.customerCompany) {
      const result: any = customerData.filter(
        (n: any) => n.customerCompany === changedValues.customerCompany,
      );
      form.setFieldsValue({
        customerPhoneNo: result[0].contactPhoneNo,
        contact: result[0].contact,
      });
    }
  };

  return (
    <Modal
      width={1024}
      afterClose={afterClose}
      destroyOnClose={true}
      confirmLoading={loading}
      title={
        editId !== undefined
          ? `编辑${disabled ? '(请先选择产品信息,才能进行其他字段编辑)' : ''}`
          : `新增${disabled ? '(请先选择产品信息,才能进行其他字段编辑)' : ''}`
      }
      visible={visible}
      onCancel={onCancel}
      onOk={onOk}
    >
      <Form
        hideRequiredMark
        style={{ marginTop: 8 }}
        form={form}
        initialValues={{
          orderType: 1,
          parentId: 0,
        }}
        name="basic"
        onValuesChange={onValuesChange}
      >
        <Row>
          <Col span={12} style={{ display: 'none' }}>
            <FormItem
              rules={[{ required: true, message: '请输入单位' }]}
              {...formItemLayout}
              label={'产品 id'}
              name="productId"
            >
              <Input disabled />
            </FormItem>
          </Col>
          <Col span={12} style={{ display: 'none' }}>
            <FormItem name="parentId">
              <Select>
                <Select.Option key={1} value={1}>
                  订单
                </Select.Option>
                <Select.Option key={2} value={2}>
                  子订单
                </Select.Option>
              </Select>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem
              {...formItemLayout}
              rules={[{ required: true, message: '请选择分公司' }]}
              label={'分公司'}
              name="productCompany"
              shouldUpdate={(prevValues, curValues) => {
                return curValues.productId !== undefined;
              }}
            >
              <Select disabled={disabled}>
                {adminCompanyType.map(item => (
                  <Select.Option key={item.value} value={item.value}>
                    {item.label}
                  </Select.Option>
                ))}
              </Select>
            </FormItem>
          </Col>
          <Col span={12}>
            <Form.Item
              rules={[{ required: true, message: '请选择品名' }]}
              {...formItemLayout}
              label={'品名'}
              name="productName"
            >
              <Select placeholder="请选择产品">
                <Select.Option value={'PET'}>{'PET'}</Select.Option>
                <Select.Option value={'PS'}>{'PS'}</Select.Option>
                <Select.Option value={'PP'}>{'PP'}</Select.Option>
                <Select.Option value={'PVC'}>{'PVC'}</Select.Option>
                <Select.Option value={'PLA'}>{'PLA'}</Select.Option>
                <Select.Option value={'ABS'}>{'ABS'}</Select.Option>
              </Select>
            </Form.Item>
          </Col>

          <Col span={12}>
            <FormItem
              rules={[{ required: true, message: '请选择颜色' }]}
              {...formItemLayout}
              label={'颜色'}
              name="color"
            >
              <Select
                showSearch
                onSearch={value => {
                  setColorSearchValue(value);
                }}
                filterOption={false}
                placeholder="请选择颜色"
              >
                {colorData &&
                  colorData.map((item: any) => (
                    <Select.Option key={item.id} value={item.color}>
                      {item.color}
                    </Select.Option>
                  ))}
              </Select>
            </FormItem>
          </Col>

          <Col span={12}>
            <FormItem
              rules={[{ required: true, message: '请选择等级' }]}
              {...formItemLayout}
              label={'等级'}
              name="grade"
            >
              <Select placeholder="请选择等级">
                <Select.Option value={'全新料'}>全新料</Select.Option>
                <Select.Option value={'仿新料'}>仿新料</Select.Option>
                <Select.Option value={'再生料'}>再生料</Select.Option>
              </Select>
            </FormItem>
          </Col>

          <Col span={12}>
            <FormItem
              {...formItemLayout}
              label={'属性'}
              name={'attribute'}
              rules={[{ required: true, message: '请选择属性' }]}
            >
              <Select
                showSearch
                onSearch={value => {
                  setAttributeSearchValue(value);
                }}
                filterOption={false}
                placeholder="请选择属性"
              >
                {attributeData &&
                  attributeData.map((item: any) => (
                    <Select.Option key={item.id} value={item.attribute}>
                      {item.attribute}
                    </Select.Option>
                  ))}
              </Select>
            </FormItem>
          </Col>

          <Col span={12}>
            <FormItem
              {...formItemLayout}
              label={'规格'}
              name="spec"
              rules={[
                ({ getFieldValue }) => ({
                  validator(rule, value) {
                    if (value) {
                      let newValue = value.split('X');
                      let tag = false;
                      let number = 0;
                      let decimal = false;

                      newValue.forEach((n: any) => {
                        let y = String(n).indexOf('.') + 1; //获取小数点的位置
                        let count = String(n).length - y; //获取小数点后的个数
                        if (n === '') {
                          number += 1;
                        }
                        if (isNaN(n * 1)) {
                          tag = true;
                        }
                        if (count > 3) {
                          tag = true;
                          decimal = true;
                        }
                      });
                      if (tag && decimal) {
                        return Promise.reject('数字仅支持 3 位小数位,请检查');
                      }
                      if (tag || number !== 0) {
                        return Promise.reject('请输入正确规格,例如 500X300');
                      }
                      return Promise.resolve();
                    } else {
                      return Promise.reject('请输入规格');
                    }
                  },
                }),
              ]}
            >
              <Input disabled={disabled} />
            </FormItem>
          </Col>

          <Col span={12}>
            <FormItem
              rules={[{ required: true, message: '请输入单位' }]}
              {...formItemLayout}
              label={'单位'}
              name="unit"
            >
              <Input disabled />
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem
              rules={[{ required: true, message: '请输入数量' }]}
              {...formItemLayout}
              label={'数量'}
              name="amount"
            >
              <Input disabled={disabled} />
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem
              shouldUpdate={(prevValues, curValues) => {
                return curValues.orderType !== undefined;
              }}
              style={{ margin: 0 }}
            >
              {({ getFieldValue }) => {
                if (getFieldValue('orderType') === 1) {
                  return (
                    <FormItem
                      {...formItemLayout}
                      label={'客户单位'}
                      rules={[{ required: true, message: '请选择客户单位' }]}
                      name="customerCompany"
                    >
                      <Select
                        showSearch
                        onSearch={value => {
                          setCustomerValue(value);
                        }}
                        filterOption={false}
                        placeholder="请选择客户单位"
                        disabled={disabled}
                      >
                        {customerData &&
                          customerData.map((item: any) => (
                            <Select.Option
                              disabled={disabled}
                              key={item.id}
                              value={item.customerCompany}
                            >
                              {item.customerCompany}
                            </Select.Option>
                          ))}
                      </Select>
                    </FormItem>
                  );
                } else {
                  return (
                    <FormItem
                      {...formItemLayout}
                      label={'客户单位'}
                      rules={[{ required: true, message: '请输入客户单位' }]}
                      name="customerCompany"
                    >
                      <Input disabled={true} />
                    </FormItem>
                  );
                }
              }}
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem
              shouldUpdate={(prevValues, curValues) => {
                return curValues.orderType !== undefined;
              }}
              style={{ margin: 0 }}
            >
              {({ getFieldValue }) => {
                if (getFieldValue('orderType') === 1) {
                  return (
                    <FormItem
                      {...formItemLayout}
                      label={'联系人'}
                      rules={[{ required: true, message: '请输入联系人' }]}
                      name="contact"
                    >
                      <Input disabled={true} />
                    </FormItem>
                  );
                } else {
                  return (
                    <FormItem
                      {...formItemLayout}
                      label={'联系人'}
                      rules={[{ required: true, message: '请输入联系人' }]}
                      name="contact"
                    >
                      <Input disabled={true} />
                    </FormItem>
                  );
                }
              }}
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem
              shouldUpdate={(prevValues, curValues) => {
                return curValues.orderType !== undefined;
              }}
              style={{ margin: 0 }}
            >
              {({ getFieldValue }) => {
                if (getFieldValue('orderType') === 1) {
                  return (
                    <FormItem
                      {...formItemLayout}
                      label={'联系方式'}
                      rules={[
                        { required: true, message: '请输入联系方式' },
                        {
                          pattern: /^[0-9\(\)\-\+]{11,}$/,
                          message: '请输入正确的联系方式',
                        },
                      ]}
                      name="customerPhoneNo"
                    >
                      <Input disabled={true} />
                    </FormItem>
                  );
                } else {
                  return (
                    <FormItem
                      {...formItemLayout}
                      label={'联系方式'}
                      rules={[{ required: true, message: '请输入联系方式' }]}
                      name="customerPhoneNo"
                    >
                      <Input disabled={true} />
                    </FormItem>
                  );
                }
              }}
            </FormItem>
          </Col>

          <Col span={12}>
            <FormItem style={{ margin: 0 }} {...formItemLayout} label={'价格'}>
              <Input.Group compact>
                <FormItem
                  rules={[{ required: true, message: '请选择价格' }]}
                  style={{ width: '40%' }}
                  name="priceType"
                >
                  <Select style={{ width: '100%' }} disabled={disabled}>
                    {adminPriceType.map(item => (
                      <Select.Option key={item.value} value={item.value}>
                        {item.label}
                      </Select.Option>
                    ))}
                  </Select>
                </FormItem>
                <FormItem
                  style={{ width: '60%' }}
                  rules={[{ required: true, message: '请输入价格' }]}
                  name={'price'}
                >
                  <Input placeholder={'价格'} disabled={disabled} />
                </FormItem>
              </Input.Group>
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem
              shouldUpdate={(prevValues, curValues) => {
                return curValues.orderType !== undefined;
              }}
              style={{ margin: 0 }}
            >
              {({ getFieldValue }) => {
                if (getFieldValue('orderType') === 1) {
                  return (
                    <FormItem
                      {...formItemLayout}
                      label={'下单时间'}
                      rules={[{ required: true, message: '请输入下单时间' }]}
                      name="orderTime"
                    >
                      <DatePicker
                        disabled={disabled}
                        style={{ width: '100%' }}
                      />
                    </FormItem>
                  );
                } else {
                  return (
                    <FormItem
                      {...formItemLayout}
                      label={'下单时间'}
                      rules={[{ required: true, message: '请输入下单时间' }]}
                      name="orderTime"
                    >
                      <DatePicker
                        disabled={disabled}
                        style={{ width: '100%' }}
                      />
                    </FormItem>
                  );
                }
              }}
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem
              shouldUpdate={(prevValues, curValues) => {
                return curValues.orderType !== undefined;
              }}
              style={{ margin: 0 }}
            >
              {({ getFieldValue }) => {
                if (getFieldValue('orderType') === 1) {
                  return (
                    <FormItem
                      rules={[{ required: true, message: '请选择状态' }]}
                      {...formItemLayout}
                      label={'状态'}
                      name="status"
                    >
                      <Select disabled={disabled}>
                        {orderStateEnumType.map((item: any) => (
                          <Select.Option key={item.value} value={item.value}>
                            {item.label}
                          </Select.Option>
                        ))}
                      </Select>
                    </FormItem>
                  );
                } else {
                  return (
                    <FormItem
                      rules={[{ required: true, message: '请选择状态' }]}
                      {...formItemLayout}
                      label={'状态'}
                      name="status"
                    >
                      <Select disabled={true}>
                        {orderStateEnumType.map((item: any) => (
                          <Select.Option key={item.value} value={item.value}>
                            {item.label}
                          </Select.Option>
                        ))}
                      </Select>
                    </FormItem>
                  );
                }
              }}
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem
              {...formItemLayout}
              label={'交货日期'}
              name="deliveryDate"
            >
              <DatePicker style={{ width: '100%' }} disabled={disabled} />
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem {...formItemLayout} label={'采购单号'} name="purchaseNo">
              <Input disabled={disabled} />
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem {...formItemLayout} label={'物料编号'} name="materialNo">
              <Input disabled={disabled} />
            </FormItem>
          </Col>
          <Col span={12}>
            <FormItem {...formItemLayout} label={'备注'} name="remark">
              <Input.TextArea disabled={disabled} />
            </FormItem>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};
export default Detail;
